package com.fxu;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.fxu.framework.core.sql.STable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * MybatisPlus 分页配置
 * @author fangxu
 * @version 1.0.0
 */
@Slf4j
@Configuration
@EnableTransactionManagement
public class MybatisDemoConfig {
    /**
     * 新的分页拦截器
     * @return 分页拦截器
     */
	@Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        log.info("MybatisPlusInterceptor");
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 开启 count 的 join 优化,只针对部分 left join
        // interceptor.setCountSqlParser(new JsqlParserCountOptimize(true));

        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            // 获取动态表名
            String dynamicTableName = STable.getTableName(); STable.clear();
            return StrUtil.isNotEmpty(dynamicTableName) ? dynamicTableName : tableName;
        });
        //以拦截器的方式处理表名称
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        //可以传递多个拦截器，即：可以传递多个表名处理器TableNameHandler
        //interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return interceptor;
    }
}